package com.probiz.estore.imports.handler.customer;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.probiz.estore.common.model.customer.Customer;
import com.probiz.estore.customer.service.CustomerManager;
import com.probiz.estore.imports.handler.ColumnHandler;
import com.probiz.estore.imports.handler.basic.ColumnBasicHandler;
import com.probiz.estore.imports.model.Column;
import com.probiz.estore.imports.model.ImportModel;

public class EmailHandler extends ColumnBasicHandler implements ColumnHandler {
	private Logger logger = Logger.getLogger(EmailHandler.class);
	
	private CustomerManager customerManager;

	public void setCustomerManager(CustomerManager customerManager) {
		this.customerManager = customerManager;
	}

	public void setProperty(ImportModel importModel, Column column)	throws Exception {
		Customer customer = (Customer)importModel.getTarget();
		String value = column.getValue();
		
		Pattern p = Pattern.compile("^([\\w-]+)(.[\\w-]+)*@([\\w-]+\\.){1,5}([A-Za-z]){2,4}$");
    	Matcher m = p.matcher(value);
    	if(!m.find()){
    		//设置结果
			importModel.setResult(ImportModel.RESULT_ERROR);
			String msg = "邮件地址不正确，无法修改导入";
			logger.error(msg);
			importModel.setMsg(msg);
			return;
    	}
		
		
		if(null != customer.getAppuserId()){
			//case:-------修改
			if(StringUtils.isNotBlank(value)){
				//检查修改后的邮件是否已经存在
				if (customerManager.getIsEmailUseByOthers(customer.getEmail(), customer.getAppuserId())) {
					//设置结果
					importModel.setResult(ImportModel.RESULT_ERROR);
					String msg = "邮件地址已被其他账户使用，无法修改导入";
					logger.error(msg);
					importModel.setMsg(msg);
					return;
				}
			}
		}else{
			//case:-------新增
			if(StringUtils.isBlank(value)){
				//设置结果
				importModel.setResult(ImportModel.RESULT_ERROR);
				String msg = "邮件地址为空，无法新增导入";
				logger.error(msg);
				importModel.setMsg(msg);
				return;
			}
			value = value.trim();
			if (customerManager.getIsEmailExist(value)) {
				//检查邮件地址是否已存在
				//设置结果
				importModel.setResult(ImportModel.RESULT_ERROR);
				String msg = "邮件地址（"+value+")已被其他账户使用，无法新增导入";
				logger.error(msg);
				importModel.setMsg(msg);
				return;
			}	
			customer.setEmail(value);
		}
		
		//设置结果
		importModel.setResult(ImportModel.RESULT_SUCCESS);
		
	}

}
